
Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath('Ext.ux', FrontSuite.options['ext_home'] + '/ux');
Ext.require([
//       'js/utils'
//     'Ext.grid.*',
//     'Ext.data.*',
//     'Ext.ux.grid.FiltersFeature',
//     'Ext.toolbar.Paging'
]);

Ext.onReady(function() {

    // Ext.QuickTips.init();

    //Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
    //    expires: new Date(new Date().getTime()+(1000*60*60*24*10)) //remember state for 10 days
    //}));

    initApp();
    var appToolbar = getAppToolbar();

    // viewport
    var viewPort = Ext.create('Ext.container.Viewport', {
        id     : 'fs.viewport',
        layout : 'fit',
        items : [{
            region : 'center',
            xtype  : 'panel',
            id     : 'fs.vp.region.tabpanel',
            html   : 'Hello world',
            tbar   : appToolbar
        }]
    });
});

// ****************************************************************************************
// * getAppToolbar()
// ****************************************************************************************

function initApp () {
    // Define the model for a Language
    Ext.regModel('Language', {
        fields: [
            {type: 'string', name: 'lang'},
            {type: 'string', name: 'text'},
            {type: 'string', name: 'icon'}
        ]
    });
}

function getAppToolbar () {

    var langData = [
        { lang: "en-US", text: "English (US)", icon: "images/flags/us.png" },
        { lang: "en-GB", text: "English (UK)", icon: "images/flags/gb.png" },
        { lang: "fr",    text: "Français",     icon: "images/flags/fr.png" },
        { lang: "es",    text: "Español",      icon: "images/flags/es.png" },
        { lang: "de",    text: "Deutsch",      icon: "images/flags/de.png" },
    ];

    // The data store holding the states
    var langStore = Ext.create('Ext.data.Store', {
        model: 'Language',
        data: langData
    });

    // Create the combo box for selecting the Language
    var langSelect = Ext.create('Ext.Button', {
        id   : 'fs.lang',
        name : 'fs.lang',
        icon : 'images/flags/us.png',
        text : 'English (US)',
        menu : langData
    });

    var loginButton = Ext.create('Ext.Button', {
        id:    'fs.loginbutton',
        text:  'Login',
        style: 'margin-left: 6px',
        width: 60,
        handler: function() {
            var usernameField = Ext.getCmp('fs.u');
            var username      = usernameField.getValue();
            var passwordField = Ext.getCmp('fs.p');
            var password      = passwordField.getValue();
            passwordField.setValue('');                       // null out the password field. we don't want the browser to offer to save it.

            var salt          = "tasty-salty-";               // TODO: fix this to the actual per-user salt
            password_sha256_16384_bits = sjcl.misc.pbkdf2(password, sjcl.codec.utf8String.toBits(salt), 16384);  // this takes a significant fraction of a second to compute
            password_sha256_16384      = sjcl.codec.hex.fromBits(password_sha256_16384_bits);                    // encode the result as text (not sure if we want to keep this around)

            var session_start_dttm = '2013-03-18 12:00:00';   // TODO: fix this to the actual session start dttm
            var session_ip_address = '192.168.1.20';          // TODO: fix this to the actual session IP address
            session_auth_token = sjcl.codec.hex.fromBits((new sjcl.misc.hmac(sjcl.codec.utf8String.toBits(session_start_dttm + '|' + session_ip_address))).encrypt(password_sha256_16384_bits));

            console.log('loginButton.handler(): u=['+username+'] password=['+password+'] token=['+session_auth_token+']');
            Ext.Ajax.request({
                url       : 'ff-auth.php',
                params    : {u : username, token : session_auth_token},
                autoAbort : false,
                success : function(response){
                    Ext.MessageBox.show({
                       title   : 'Login Status',
                       msg     : 'Login Successful',
                       buttons : Ext.MessageBox.OK
                    });
                },
                failure: function(response, opts) {
                    Ext.MessageBox.show({
                       title   : 'Login Status',
                       msg     : 'Login Error: ' + response.status,
                       buttons : Ext.MessageBox.OK
                    });
                }
            });
            //var frmLogin = this.up('form').getForm();
            //if (frmLogin.isValid()) {
            //    frmLogin.submit({
            //        url: 'ff-auth.php',
            //        waitMsg: 'Submitting your credentials',
            //        success: function(form, action) {
            //            // opens the menu page returned by the server, php validation of security sets menu for the user
            //            // oCurrentUser = {name: action.result.username, email: action.result.usermail, sms: action.result.usersms};
            //            oCurrentUser = {username: action.result.username};
            //            alert('Is this you ?\n\n' + oCurrentUser.username);
            //            location.href = action.result.redirect;
            //        },
            //        failure: function(form, action) {
            //            Ext.Msg.alert('Failure', action.result.errormsg);
            //            if (action.failureType === Ext.form.action.Action.CONNECT_FAILURE) {
            //                Ext.Msg.alert('Error',
            //                    'Status:'+action.response.status+': '+
            //                    action.response.statusText);
            //            }
            //            if (action.failureType === Ext.form.action.Action.SERVER_INVALID){
            //                // server responded with success = false
            //                Ext.Msg.alert('Invalid', action.result.errormsg);
            //            }
            //        }
            //    })
            //}
        }
    });

    // Create the combo box for selecting the Language
    var helpMenu = Ext.create('Ext.Button', {
        // id: 'fs.helpMenu',
        // name: 'fs.helpMenu',
        // icon : 'images/misc/gear.png',
        text : 'Help',
        menu : [
            'About'
        ]
    });

    // Create the combo box for selecting the Language
    var settingsMenu = Ext.create('Ext.Button', {
        // id: 'fs.settingsMenu',
        // name: 'fs.settingsMenu',
        // icon : 'images/misc/gear.png',
        text : 'Settings',
        menu : [
        ]
    });

    var loginBox = Ext.create('Ext.container.Container', {
        layout: {
            type: 'table',
            columns: 5,
        },
        items: [
            langSelect,
            { xtype: 'textfield',
              name: 'fs.u',
              id: 'fs.u',
              style: 'margin-bottom: 0px; margin-left: 6px;',
              fieldLabel: 'Username',
              labelSeparator: ':',
              labelAlign: 'right',
              labelWidth: 60,
              labelPad: 2,
              width: 160
            },
            { xtype: 'textfield',
              name: 'fs.p',
              id: 'fs.p',
              inputType: 'password',
              style: 'margin-bottom: 0px; margin-left: 6px;',
              fieldLabel: 'Password',
              labelSeparator: ':',
              labelAlign: 'right',
              labelWidth: 60,
              labelPad: 2,
              width: 160
            },
            loginButton,
            helpMenu,
            { xtype: 'label', text: '' },
            { xtype: 'label', text: 'Register for a new account?',
              tdAttrs: { style: { 'text-align': 'left' } },
              style: 'margin-bottom: 1px; margin-left: 12px;'
            },
            { xtype: 'label', text: 'Forgot your password?',
              tdAttrs: { style: { 'text-align': 'left' } },
              style: 'margin-bottom: 1px; margin-left: 14px;'
            },
            { xtype: 'checkbox',
              name: 'fs.kli2',
              id: 'fs.kli2',
              style: 'margin-bottom: 1px; margin-left: 6px;',
              hideLabel: true,
              boxLabel: 'Remain logged in',
              boxLabelAlign: 'after',
              width: 120,
              colspan: 2
            }
        ]
    });

    // images/wallpapers/aurora_borealis_2-wallpaper-1280x1024.jpg
    // images/wallpapers/digital_world_access.jpg
    // images/wallpapers/orbiting_sparkles_around_earth.jpg
    // images/wallpapers/aurora_burst_lime_green-wallpaper-1600x900.jpg
    // images/wallpapers/inside_digital_donut.jpg
    // images/wallpapers/os_x_mountain_lion-wallpaper-1280x1024.jpg
    // images/wallpapers/blue_rays.jpg
    // images/wallpapers/internet_business_23-wallpaper-1280x1024.jpg
    // images/wallpapers/swooshing_pattern.jpg
    // images/wallpapers/Breakwater_1366x768_laptop.jpg
    // images/wallpapers/internet_security.jpg
    // images/wallpapers/worldwide_neon_web.jpg

    var appToolbar = Ext.create('Ext.toolbar.Toolbar', {
        id : 'fs.apptoolbar',
        enableOverflow: true,
        // resizeable: true,
        // resizeHandles: 'all',
        style: 'background-image: url("images/wallpapers/blue_rays.jpg")',
        items: [
            // { xtype: 'label', text: 'Home' },
            // '-',
            // { xtype: 'label', text: 'Group:' },
            // '-',
            // { xtype: 'label', text: 'Location:' },
            // '-',
            // settingsMenu,
            // '-',
            // { xtype: 'button', text:  'Logout' },
            '->',
            loginBox
        ]
    });

    //function attemptLogin (a, b, c, d, e) {
    //    console.log(a,b,c,d,e);
    //}

    //var map = new Ext.util.KeyMap({ target: Ext.getCmp('fs.u'), key: 13, fn: attemptLogin });
    //var map = new Ext.util.KeyMap({ target: Ext.getCmp('fs.p'), key: 13, fn: attemptLogin });

    return(appToolbar);
}

